<template>
  <div class="dailyTask" v-title data-title="缺陷任务单新增页面">
    <home-nav :userData="userinfo"></home-nav>
    <div class="navigator">
      <div class="baseinfo">
        <div style="display: flex">
          <span style="margin: 0px auto 30px auto; font-weight: bold; font-size: 20px">新增缺陷任务单</span>
          <span style="color: #31a0e1" v-show="id" @click="openHistory">操作日志</span>
        </div>
        <div class="info-title">关联的任务单信息</div>
        <a-form-model class="hte-form-model" ref="ruleForm" :model="form">
          <div v-show="form.taskBuildType != '3'">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="任务单编号">
                  <a-input v-model="form.taskNo" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="任务单分类">
                  <a-input v-model="form.taskTypeName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="任务单名称">
                  <a-input v-model="form.taskName" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="创建人">
                  <a-input v-model="form.createUserName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item class="disable-input-bg" label="创建时间">
                  {{ dateFormat(form.createDate) }}
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="主导团队">
                  <a-input v-model="form.mainDeptName" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item ref="taskBuildType" label="任务单类型" prop="taskBuildType">
                  <a-radio-group v-model="form.taskBuildType" disabled>
                    <a-radio value="1">个人</a-radio>
                    <a-radio value="2">团队</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>

              <a-col :span="8" v-if="form.taskType == '30'">
                <a-form-model-item label="产品系统">
                  <a-input v-model="form.productSystemName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="form.taskType == '30'">
                <a-form-model-item label="迭代负责人">
                  <a-input v-model="form.handlerName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item class="disable-input-bg" label="任务开始时间">
                  {{ dateFormat(form.startDate) }}
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="任务计划完成时间" class="disable-input-bg">
                  {{ dateFormat(form.endDate) }}
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="form.taskType == '30'">
                <a-form-model-item label="版本号">
                  <a-input v-model="form.versionNo" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" v-if="form.taskType == '30'">
              <a-col :span="24">
                <a-form-model-item ref="hasSendNotice" label="是否已上线" prop="hasSendNotice">
                  <a-tooltip>
                    <template slot="title">
                      <span
                        >是否已上线是指【整个任务单的完成状态是以该字段为准，即使所有子任务已完成】<br />当所有子任务和缺陷都完成时，任务单创建人或迭代负责人可修改该状态。</span
                      >
                    </template>
                    <a-radio-group v-model="form.hasSendNotice" disabled>
                      <a-radio value="1">未完成</a-radio>
                      <a-radio value="2">已完成并且已发通知</a-radio>
                      <a-radio value="3">已完成但无需发通知</a-radio>
                    </a-radio-group>
                  </a-tooltip>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="开放范围:">
                  <a-textarea
                    v-model="form.openRangeName"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    style="width: 100%"
                    disabled
                    readOnly
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="任务单完成目标:">
                  <a-textarea
                    v-model="form.target"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                    style="width: 100%"
                    disabled
                    readOnly
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
          <div v-show="form.taskBuildType == '3'">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="任务单编号">
                  <a-input v-model="form.taskNo" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="任务单名称">
                  <a-input v-model="form.taskName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目信息">
                  <a-input v-model="projectNoAndName" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目节点" prop="timeNodeCode">
                  <a-select
                    v-model="form.timeNodeCode"
                    placeholder="请选择未报工的项目节点"
                    :options="timeNodeCodeOptions"
                    notFoundContent="请先选择项目"
                    disabled
                    style="width: 100%"
                  >
                    <a-icon slot="suffixIcon" type="plus" />
                  </a-select>
                </a-form-model-item>
              </a-col>
              <div v-if="form.projectNo != ''">
                <a-col :span="8" v-if="form.taskType == '30'">
                  <a-form-model-item label="产品系统">
                    <a-input v-model="form.productSystemName" disabled />
                  </a-form-model-item>
                </a-col>

                <a-col :span="8" v-if="form.projectNo != '' && form.taskType == '30'">
                  <a-form-model-item label="迭代负责人">
                    <a-input v-model="form.handlerName" disabled />
                  </a-form-model-item>
                </a-col>

                <a-col :span="8">
                  <a-form-model-item label="创建人">
                    <a-input v-model="form.createUserName" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="创建时间" class="disable-input-bg">
                    {{ form.createDate ? timeFormat(form.createDate) : nowDate }}
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="主导经营体">
                    <a-input v-model="form.mainDeptName" disabled />
                  </a-form-model-item>
                </a-col>
              </div>
              <div v-if="form.timeNodeCode">
                <a-col :span="8">
                  <a-form-model-item class="disable-input-bg" label="节点开始时间">
                    {{ timeFormat(form.startDate) }}
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item class="disable-input-bg" label="节点完成时间">
                    {{ timeFormat(form.endDate) }}
                  </a-form-model-item>
                </a-col>
                <a-col :span="8" v-if="form.projectNo != '' && form.taskType == '30'">
                  <a-form-model-item label="版本号">
                    <a-input v-model="form.versionNo" disabled />
                  </a-form-model-item>
                </a-col>
              </div>
            </a-row>
            <a-row :gutter="24" v-if="form.taskType == '30'">
              <a-col :span="8">
                <a-form-model-item ref="businessConfirm" label="需要审批确认" prop="businessConfirm">
                  <a-input :value="form.businessConfirm == '1' ? '是' : '否'" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item ref="hasSendNotice" label="是否已上线" prop="hasSendNotice">
                  <a-input
                    :value="
                      form.hasSendNotice == '1'
                        ? '未完成'
                        : form.hasSendNotice == '2'
                        ? '已完成并且已发通知'
                        : '已完成但无需发通知'
                    "
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item ref="testUserName" label="测试员" prop="testUserName">
                  <a-input :value="form.testUserName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item ref="qualityScore" label="质量分" prop="qualityScore">
                  <a-input v-model="form.qualityScore" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item ref="testConfirmDate" class="disable-input-bg" label="测试时间" prop="testConfirmDate">
                  {{ timeFormat(form.testConfirmDate) }}
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" v-if="form.taskType == '30'">
              <a-col :span="24">
                <a-form-model-item label="测试结果">
                  <a-textarea
                    v-model="form.testConfirm"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    style="width: 100%"
                    disabled
                    readOnly
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="开放范围:">
                  <a-textarea
                    v-model="form.openRangeName"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    style="width: 100%"
                    disabled
                    readOnly
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" v-if="form.timeNodeCode">
              <a-col :span="24">
                <a-form-model-item label="任务单完成目标:">
                  <a-textarea
                    v-model="form.target"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                    style="width: 100%"
                    disabled
                    readOnly
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
          <a-divider style="margin: 20px 0" />

          <div class="info-title">
            相关附件
            <ht-upload
              ref="myUpload"
              class="upload-demo"
              multiple
              dbKey="Trd"
              busField="workTask"
              busType="workTask"
              :busKey="busKeyId"
              ftpKey="ftp"
              v-model="fileList"
              :show-file-list="false"
            >
              <a-button type="primary"><a-icon type="plus" />新增附件</a-button>
            </ht-upload>
            <span>
              <img src="@/assets/attention-red.png" alt="" style="width: 12px; margin: 0px 5px 0px 5px" />
              <span style="font-size: 14px"
                >附件非必填，如有相关附件可以上传，例如收益计算明细，计算方法，该任务单的方案、规划、工作要求等。</span
              >
            </span>
          </div>
          <div style="margin-top: 10px">
            <a-table
              class="hte-table-content"
              :columns="uploadColumns"
              :data-source="fileQueryList"
              :pagination="false"
              :rowKey="
                (record, index) => {
                  return index
                }
              "
              bordered
              size="middle"
              v-show="fileQueryList.length > 0"
            >
              <a
                slot="name"
                slot-scope="text, record"
                @click="previewAttach(record.id, record.fileName)"
                href="javascript:void(0)"
                title="点击预览附件"
                style="color: blue"
                >{{ text }}</a
              >
              <span slot="uploadTime" slot-scope="text">
                {{ timeFormat(text) }}
              </span>
              <span slot="aciton" slot-scope="text, record">
                <span
                  style="color: blue; cursor: pointer"
                  @click="deletefj(record.id)"
                  type="primary"
                  v-if="record.uploader == currentUserId"
                  >删除</span
                >
                <span
                  style="color: blue; cursor: pointer; margin-left: 5px"
                  @click="doDownLoadBatch(record.id)"
                  type="primary"
                  >下载</span
                >
              </span>
            </a-table>
          </div>

          <a-divider style="margin: 20px 0" />

          <div>
            <div class="info-title">
              缺陷明细
              <a-button type="primary" @click="kpiAdd()">新增</a-button>
              <a-button style="margin-left: 15px" @click="kpiDel()">删除</a-button>
            </div>
            <a-table
              class="hte-table-content"
              :row-selection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                getCheckboxProps: getCheckboxProps,
              }"
              :columns="kpi.columns"
              :data-source="kpi.data"
              :rowKey="
                (record, index) => {
                  return index
                }
              "
              bordered
              size="middle"
              :pagination="false"
            >
              <template slot="taskContent" slot-scope="text, record, index">
                <a-textarea
                  v-model="record.taskContent"
                  placeholder="请输入缺陷内容，500字以内"
                  :auto-size="{ minRows: 1, maxRows: 7 }"
                  :maxLength="500"
                  @change="checkValueLen(record.taskContent, 500, index, 'taskContent')"
                  :readOnly="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id) ? true : false"
                />
              </template>
              <template slot="bugLevel" slot-scope="text, record">
                <a-select
                  v-model="record.bugLevel"
                  placeholder="请选择缺陷等级"
                  :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"
                >
                  <a-icon slot="suffixIcon" type="plus" />
                  <a-select-option value="1">致命</a-select-option>
                  <a-select-option value="2">严重</a-select-option>
                  <a-select-option value="3">一般</a-select-option>
                  <a-select-option value="4">提示/建议</a-select-option>
                </a-select>
              </template>
              <template slot="startDate" slot-scope="text, record">
                <a-date-picker
                  v-model="record.startDate"
                  placeholder="请输入修复开始时间"
                  :allowClear="false"
                  @change="
                    (date, dateString) => {
                      timeSelect(date, dateString, record, 1)
                    }
                  "
                  :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"
                />
              </template>
              <template slot="endDate" slot-scope="text, record">
                <!-- :disabled-date="disabledStartDate"  -->
                <a-date-picker
                  v-model="record.endDate"
                  placeholder="请输入修复完成时间"
                  :allowClear="false"
                  @change="
                    (date, dateString) => {
                      timeSelect(date, dateString, record, 2)
                    }
                  "
                  :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"
                />
              </template>
              <template slot="handleUserName" slot-scope="text, record">
                <a-select
                  show-search
                  :value="record.handleUserName"
                  placeholder="输入账号或者名称查找用户"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                  @search="fetchUser"
                  @change="
                    (value, option) => {
                      handleSubChange(value, option, record)
                    }
                  "
                  :disabled="(record.detailStatus == '2' || !(record.handleUserId == currentUserId || form.createUserId === currentUserId ) && record.id &&form.id)? true : false"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="(d, index) in userData" :key="index" :value="d.username">
                    {{ d.realname }}({{ d.username }})
                  </a-select-option>
                </a-select>
              </template>
            </a-table>
          </div>
        </a-form-model>
        <div class="btn-box">
          <a-button style="margin-right: 15px" @click="doSubmit()">保存</a-button>
          <a-button style="margin-right: 15px" @click="sendTask" v-show="form.id != '' && form.status != '1'"
            >发送娅米消息通知</a-button
          >
        </div>
      </div>
    </div>
    <a-modal
      v-model="visibleModelHistory"
      width="70vw"
      :bodyStyle="{ padding: '10px', backgroundColor: '#f4f5fa' }"
      title="变更历史"
      :footer="null"
      :key="id"
    >
      <task-change-history :hid="id"></task-change-history>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction,previewAttach } from '@/api/manage'
import moment from 'moment'
import '@/config/upload.install.js'
import Vue from 'vue'
import { Modal } from 'ant-design-vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { getParamValFromUrl, formatFileSize, endWith } from '@/utils/common.js'
import { simpleDebounce } from '@/utils/util'

const uploadColumns = [
  {
    title: '附件名称',
    dataIndex: 'fileName',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '上传人',
    dataIndex: 'uploaderName',
    width: '10%',
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    align: 'center',
    width: '15%',
    scopedSlots: { customRender: 'uploadTime' },
  },
  {
    title: '操作',
    dataIndex: 'aciton',
    align: 'center',
    scopedSlots: { customRender: 'aciton' },
    width: '10%',
  },
]

export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    TaskChangeHistory: () => import('@views/myTask/TaskChangeHistory'),
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'dailyBugTaskAdd',
      },
      uploadColumns,
      selectedRowKeys: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      tableSelectKey: '',
      form: {
        id: '',
        taskType: '30',
        taskTypeName: '',
        taskBuildType: '2',
        taskBugType: '',
        taskName: '',
        startDate: '',
        endDate: '',
        createUserId: '',
        createUserName: '',
        mainDeptId: '',
        mainDeptName: '',
        target: '',
        saveFlag: true,
        status: '',
        taskNo: '',
        versionNo: '',
        handlerId: '',
        handlerName: undefined,
        hasSendNotice: '1',
        openRange: '',
        openRangeName: '',
        productSystem: '',
        productSystemName: '',
        taskBugLevel: undefined,
        projectBuildId: '',
        projectNo: '',
        projectName: '',
        timeNodeCode: '',
        projectTypeSubCategory: '',
      },
      url: {
        saveBugList: '/projectWorkTask/saveBugList',
        getAttachInfo: '/tp/attach/getAttaches',
        getWorkTask: '/projectWorkTask/queryByBugId',
        sendTaskByBugId: '/projectWorkTask/sendTaskByBugId',
        codeInfoList: '/manage/codeInfo/list',
        getUserList: '/lib/hteFileClass/getUserListOnlyUpms',
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/tp/attach/delete',
        initTimeNodeOption: '/projectBuildTime/queryListByBuildId',
        getProjectBuildById: '/projectBuild/queryById',
      },
      kpi: {
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 50,
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '缺陷内容',
            dataIndex: 'taskContent',
            align: 'center',
            scopedSlots: { customRender: 'taskContent' },
          },
          {
            title: '缺陷等级',
            dataIndex: 'bugLevel',
            align: 'center',
            width: '15%',
            scopedSlots: { customRender: 'bugLevel' },
          },
          {
            title: '修复开始时间',
            dataIndex: 'startDate',
            align: 'center',
            width: '15%',
            scopedSlots: { customRender: 'startDate' },
            sorter: (a, b) => a.startDate.localeCompare(b.startDate),
          },
          {
            title: '修复完成时间',
            dataIndex: 'endDate',
            align: 'center',
            width: '15%',
            scopedSlots: { customRender: 'endDate' },
            sorter: (a, b) => a.endDate.localeCompare(b.endDate),
          },
          {
            title: '具体执行人员',
            dataIndex: 'handleUserName',
            align: 'center',
            scopedSlots: { customRender: 'handleUserName' },
            width: '15%',
          },
        ],
        data: [],
        selRowIds: [],
      },
      fileList: [],
      fileQueryList: [],
      id: '',
      addFlag: false,
      nowDate: moment().format('YYYY-MM-DD'),
      currentUserId: '',
      productSystemOptions: [],
      fetching: false,
      userData: [],
      userOpenData: [],
      userHandleData: [],
      casProductSystemOptions: [],
      casModel: [],
      busKeyId: this.id + '_bugId',
      projectNoAndName: '',
      timeNodeCodeOptions: [],
      visibleModelHistory: false,
    }
  },
  created() {
    const obj = this.$route.query
    this.id = obj.id
    this.initData(this.id)
    this.currentUserId = Vue.ls.get(USER_INFO).username
  },
  methods: {
    initTimeNodeOption(id) {
      var vm = this
      vm.timeNodeCodeOptions = []
      //vm.form.timeNodeCode = ''
      getAction(vm.url.initTimeNodeOption, { projectBuildId: id }).then((res) => {
        if (res.code === 200) {
          vm.timeListData = res.result || []
          let newarr = vm.timeListData.filter((item) => {
            return item.reportStatus == null || item.reportStatus != '2'
          })
          newarr.forEach((element) => {
            vm.timeNodeCodeOptions.push({
              label: element.timeNode,
              value: element.timeNodeCode,
            })
          })
        } else {
          //const msg = res.message == null ? res.data : res.message;
          this.$message.error(res.message)
        }
      })
    },
    fetchUser(val) {
      if (val) {
        this.userData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userData = res.result
            this.fetching = false
          }
        })
      }
    },
    // 明细处理人
    handleSubChange(value, option, record) {
      let index = this.kpi.data.findIndex((item) => item.key === record.key)
      if (index != -1) {
        this.kpi.data[index].handleUserId = value
        let text = option.componentOptions.children[0].text.trim();
        let realText = text ? text.split("(")[0] : "";
        this.kpi.data[index].handleUserName = realText
      }
    },
    dateFormat(date) {
      return date ? moment(date).format('YYYY-MM-DD') : ''
    },
    // 实时校验长度
    checkValueLen: simpleDebounce(function (val, len, index, key) {
      if (!val) return
      const leng = val.length
      const obj = this.kpi.data[index]
      if (leng > len) {
        obj[key] = val.slice(0, len)
        this.$set(this.kpi.data, index, obj)
        this.$message.warning(`输入内容超出${len}长度，将自动进行截取`)
      }
    }, 500),
    timeFormat(time) {
      if (time) {
        return moment(time).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    disabledStartDate(current) {
      return current.isoWeekday() == 6 || current.isoWeekday() == 7
    },
    timeSelect(date, dateString, record, id) {
      let startDateStr = record.startDate ? moment(record.startDate).format('YYYY-MM-DD') : record.startDate
      let endDateStr = record.endDate ? moment(record.endDate).format('YYYY-MM-DD') : record.endDate
      if (startDateStr && startDateStr != '' && endDateStr && endDateStr != '') {
        if (moment(startDateStr).diff(moment(endDateStr), 'days') > 0) {
          this.$message.warning('开始时间不能大于完成时间')
          if (id === 1) {
            this.kpi.data.forEach((item) => {
              if (item.key === record.key) {
                item.startDate = ''
              }
            })
          } else {
            this.kpi.data.forEach((item) => {
              if (item.key === record.key) {
                item.endDate = ''
              }
            })
          }
          return
        }
        // if (this.form.taskType == '30') {
        //   //完成时间不能大于开始时间3天
        //   let momStartDate = moment(startDateStr)
        //   let momEndDate = moment(endDateStr)
        //   let days = momEndDate.diff(momStartDate, 'days') + 1
        //   if (days > 3) {
        //     while (momEndDate.diff(momStartDate, 'days') + 1 != 0) {
        //       if (momStartDate.isoWeekday() == 6 || momStartDate.isoWeekday() == 7) {
        //         days -= 1
        //       }
        //       momStartDate.add(1, 'days')
        //     }
        //   }
        //   if (days > 3) {
        //     this.$message.warning('完成时间不能大于开始时间3天')
        //     if (id === 1) {
        //       this.kpi.data.forEach((item) => {
        //         if (item.key === record.key) {
        //           item.startDate = ''
        //         }
        //       })
        //     } else {
        //       this.kpi.data.forEach((item) => {
        //         if (item.key === record.key) {
        //           item.endDate = ''
        //         }
        //       })
        //     }
        //     return
        //   }
        // }
      }
      if (id === 1) {
        if (!startDateStr) {
          this.$message.warning('请填写子任务单开始时间')
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.startDate = ''
            }
          })
          return
        }
        this.kpi.data.forEach((item) => {
          if (item.key === record.key) {
            item.startDate = dateString
          }
        })
      } else {
        if (!endDateStr) {
          this.$message.warning('请填写子任务单结束时间')
          this.kpi.data.forEach((item) => {
            if (item.key === record.key) {
              item.endDate = ''
            }
          })
          return
        }
        this.kpi.data.forEach((item) => {
          if (item.key === record.key) {
            item.endDate = dateString
          }
        })
      }
    },
    kpiAdd() {
      this.kpi.data.unshift({
        key: this.kpi.data.length + 1 + new Date().getTime(),
        taskContent: '',
        bugLevel: undefined,
        startDate: '',
        endDate: '',
        handleUserId: undefined,
        handleUserName: undefined,
      })
    },
    kpiDel() {
      if (this.kpi.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的明细记录')
        return
      }

      if (this.kpi.data.length == 1) {
        this.$message.warning('该任务单只有一条子任务，不能删除')
        return
      }
      const that = this;
      Modal.confirm({
        title: '提示',
        content: '删除子任务之前请先保存任务信息，避免数据丢失',
        onOk() {
          const list = that.kpi.selRowIds.map(function (item) {
            return item.id
          })
          that.delAjax(list)
          that.kpi.selRowIds = []
          that.selectedRowKeys = [] 
        },
        onCancel() {},
      })
    },
    delAjax(list) {
      // todo ajax 刷新整个页面 
      postAction('/projectWorkTask/detailBatchDelete', {"list":list,"taskBuildType":2})
      .then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.initData(this.form.id)
        } else {
          const msg = res.message == null ? res.result : res.message
          this.$message.error(msg)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    sendTask() {
      getAction(this.url.sendTaskByBugId, { bugId: this.id })
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('发送成功')
          } else {
            const msg = res.message == null ? res.result : res.message
            this.$message.error(msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    doSubmit() {
      let flag = false
      const that = this

      if (this.kpi.data.length > 0) {
        this.kpi.data.forEach((item) => {
          if (
            item.taskContent === '' ||
            item.startDate === '' ||
            item.endDate === '' ||
            item.bugLevel === '' ||
            item.handleUserName === '' ||
            item.handleUserId === '' ||
            !item.handleUserId
          ) {
            flag = true
          }
          item.bugId = that.id
        })
      }

      if (this.kpi.data.length == 0 || flag) {
        this.$message.error('缺陷明细没填写完整')
        return
      }
      this.form.detail = this.kpi.data
      postAction(that.url.saveBugList, that.form)
        .then((res) => {
          if (res.code === 200 && res.result) {
            that.$message.success('保存成功', 5)
            that.$router.push({ path: '/dailyBugTaskAdd', query: { id: res.result } })
          } else {
            const msg = res.message == null ? res.result : res.message
            that.$message.error(msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    initData(id) {
      getAction(this.url.getWorkTask, { id: id }).then((res) => {
        if (res.code === 200 && res.result) {
          this.form = res.result
          console.log(this.form)
          this.kpi.data = res.result.detail
          this.kpi.data.forEach((item, index) => {
            item.key = index + 1
          })
          if (this.form.taskBuildType == '3') {
            this.initTimeNodeOption(res.result.projectBuildId)
            getAction(this.url.getProjectBuildById, { id: this.form.projectBuildId }).then((resProject) => {
              this.form.projectNo = resProject.result.projectNo
              this.form.projectName = resProject.result.projectName
              this.projectNoAndName = resProject.result.projectNo + ' && ' + resProject.result.projectName
            })
          }
          this.loadAttachInfo()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    loadAttachInfo() {
      getAction(this.url.getAttachInfo, {
        dbKey: 'Trd',
        busKey: this.busKeyId,
        busField: 'workTask',
        busType: 'workTask',
        ftpKey: 'ftp',
      }).then((res) => {
        this.fileQueryList = res.data || []
      })
    },
    previewAttach(attachId, fileName) {
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.doDownLoadBatch(attachId)
        return
      }

      let params={
        id:attachId,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        let downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      let iframe = document.getElementById('_attachToolView_downloadfile_frame')
      iframe.src =
        this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
    },
    // 绑busKey
    bindBusKey() {
      if (this.fileList.length > 0) {
        const ids = this.fileList.map(function (item) {
          return item.id
        })
        const jsona = { dbKey: 'Trd', id: ids.toString(), busKey: this.busKeyId }
        var jsonStr = JSON.stringify(jsona)
        this.$refs.myUpload.bindBusKey(jsonStr)
      }
    },
    deletefj(id) {
      const that = this
      this.$confirm({
        title: '是否确认删除？',
        onOk() {
          postAction(that.url.deleteBatch, { id: id, busField: 'workTask', busType: 'workTask', ftpKey: 'ftp' })
            .then((res) => {
              if (res.code == 1) {
                that.$message.success('删除成功')
                that.fileQueryList.splice(
                  that.fileQueryList.findIndex((item) => item.id === id),
                  1
                )
                that.fileList.splice(
                  that.fileList.findIndex((item) => item.id === id),
                  1
                )
              } else {
                that.$message.warning('删除失败:' + res.msg)
              }
            })
            .catch((res) => {
              that.$message.warning('删除失败:' + res.msg)
            })
        },
        onCancel() {},
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.kpi.selRowIds = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: (record.detailStatus == '2' || !(record.handleUserId == this.currentUserId || this.form.createUserId === this.currentUserId ) && record.id && this.form.id)? true : false
        },
      }
    },
    openHistory() {
      this.visibleModelHistory = true
    },
  },
  watch: {
    fileList: function (newQuestion, oldQuestion) {
      // this.bindBusKey()
      newQuestion.forEach((item) => {
        var newIndex = this.fileQueryList.findIndex((item2) => item2.id === item.id)
        if (newIndex == -1) {
          this.fileQueryList.push(item)
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.dailyTask {
  height: 100%;
  font-size: 14px;
  .navigator {
    min-height: 100%;
    padding: 27px 125px 50px;
    background-color: #f5f5f5;
  }
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  margin-top: 20px;
  .btn-box {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
}
.info-title {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 14px;
  color: #333333;
  margin-bottom: 14px;
  &:before {
    content: '';
    position: absolute;
    display: block;
    height: 70%;
    top: 15%;
    width: 3px;
    left: 0;
    background-color: #47a4fa;
  }
  /deep/ .ant-btn {
    margin-left: 10px;
    height: 30px;
    line-height: 30px;
  }
}
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .ant-calendar-picker {
  width: 100%;
}
/deep/ .upload-demo {
  display: inline-block;
}
@media (max-width: 1080px) {
  .dailyTask .navigator {
    padding: 27px 30px 50px !important;
  }
}
</style>